<script setup lang="ts">
import { onMounted,ref } from 'vue';
import HelloWorld from './components/HelloWorld.vue'
import { createEditor } from './components/MdEditor';
import { EditorView } from '@codemirror/view';
import MittUtils from './components/MittUtils';
const editorView = ref<EditorView>()
const editorHead = ref(0)
onMounted(()=>{
  // 因为要获取dom，需要在onMounted中执行
  editorView.value =  createEditor({
    doc:"# Hello Markdown",
    parent: document.querySelector("#markdownEditor")!
  })
  // editorView.focus();
  // editorView.dispatch({
  //   changes: {from: 0, insert: "# 欢迎使用！"},
  //   selection: { 
  //     head:4,
  //     anchor:2
  //   }
  // })
})
MittUtils.on('change',(data:any)=>{
  editorHead.value = data.head;
})
const insertContent = ()=>{
  const editor = editorView.value as EditorView
  if(editor){
     console.log("-------hasFocus----------" + editor.hasFocus)
     editor.dispatch({
      changes: {from: editorHead.value , insert: `I am inserted!\n`},
      selection: {
        anchor: editorHead.value + '<h1>I am inserted!'.length
      }
    })
    editor.focus()
  }
}

</script>
<template>
<div>
  <hello-world></hello-world>
  <hr style="margin-top: 10px;">
  <div id="markdownEditor" class="markdown-editor"></div>

  <button @click="insertContent">
    插入图片
  </button>
</div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 10px;
}
* {
  box-sizing: border-box;
}
</style>
